//
//  BootViewController.swift
//  Duyiguqin
//
//  Created by zhangzhao on 2024/10/17.
//

import UIKit
import Alamofire
import SDWebImage

class BootViewController: UIViewController {
        
    private lazy var imageView: UIImageView = {
        let v = UIImageView()
        v.contentMode = .scaleAspectFill
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.edges.equalTo(UIEdgeInsets.zero)
        }
        AF.request(URL(string: "http://tiaoyin.dyxt.org/du1/system/music/getStartupInfo")!).response { [weak self] response in
            if let data = response.data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let dict = json["data"] as? [String: Any], let accessUrl = dict["accessUrl"] as? String, let url = URL(string: accessUrl) {
                SDWebImageManager.shared.loadImage(with: url, progress: nil) { image, _, _, _, _, _ in
                    if let img = image {
                        DispatchQueue.main.async {
                            self?.imageView.image = img
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: DispatchWorkItem(block: {
                                self?.showMainController()
                            }))
                        }
                    } else {
                        self?.showMainController()
                    }
                }
            } else {
                self?.showMainController()
            }
        }
    }

    private func showMainController() {
        let tabbar = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "BootTabBarViewController")
        if let windowScene = UIApplication.shared.connectedScenes
                .first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene {
            if let window = windowScene.windows.first(where: { $0.isKeyWindow }) {
                window.rootViewController = tabbar
                window.makeKeyAndVisible()
                return
            }
        }
    }
}
